from django.db.transaction import atomic
from django.http import HttpRequest, HttpResponse
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from education.models import User, Idcard
from other.serializers import UserSimpleSerializer, UserDetailSerializer
from other.utils import check_name, check_id


class UserAddressViewSet(ModelViewSet):
    """用户地址视图集"""
    queryset = User.objects.all()
    serializer_class = UserSimpleSerializer

    def perform_destroy(self, instance):
        instance.address = ''
        instance.save()


class UserViewSet(ModelViewSet):
    """用户个人信息视图集"""
    queryset = User.objects.all()
    serializer_class = UserDetailSerializer


# @api_view(('GET', 'POST'))
# @authentication_classes((LoginRequiredAuthentication, ))
# def change_user_info(request: HttpRequest) -> HttpResponse:
#     """更改用户信息"""
#     uid = int(request.token.user.userid)
#     user = User.objects.get(userid=uid)
#     username = request.data.get('username')
#     city = request.data.get('city')
#     tel = request.data.get('tel')
#     tel = '13566554433'
#     email = request.data.get('email')
#     address = request.data.get('address')
#     user.username = username
#     user.city = city
#     user.tel = tel
#     user.email = email
#     user.address = address
#     user.save()
#     data = {'code': 30000, 'message': '更新成功'}
#     return Response(data)

@api_view(('POST',))
# @authentication_classes((LoginRequiredAuthentication, ))
def name_authentication(request: HttpRequest) -> HttpResponse:
    """实名认证"""
    realname = request.data.get('realname')
    idnum = request.data.get('idnum')
    # user = User.objects.only('is_certificated').get(userid=request.user.no)
    if check_name(realname) and check_id(idnum):
        username = 'wenge'
        idcard = Idcard()
        idcard.realname = realname
        idcard.idnum = idnum
        user = User.objects.only('userid').get(username=username)
        idcard.user = user
        user.is_certificated = 1
        with atomic():
            idcard.save()
            user.save()
        data = {'code': 20000, 'message': '实名认证成功'}
    else:
        data = {'code': 20001, 'message': '姓名或身份证号输入有误'}
    return Response(data)
